using System.Linq;
using System.Web.Mvc;
using Quickie.Models;
using Quickie.Models.IoC;
using Quickie.Models.Data;
using Quickie.Models.Entities;
using Quickie.Models.ViewModel;
using Quickie.Models.Interfaces;

namespace Quickie.Areas.Admin.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class CategoryAdminController : Controller
    {
        private IRepository<Category> categories;
        private IRepository<Product> products;

        public CategoryAdminController(IRepository<Category> cats, IRepository<Product> prods)
        {
            categories = cats;
            products = prods;
        }

        public ActionResult List()
        {
            var model = categories.GetAll().ToList();
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var category = categories.GetByID(id);
            PopulateViewData(id,category.ParentID ?? 0);
            return View(category);
        }

        public ActionResult New()
        {
            var model = new Category();
            PopulateViewData(0,0);
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            Category categoryToDelete = categories.GetByID(id);
            categories.Delete(categoryToDelete);
            categories.SaveChanges();

            return Redirect(Url.Action("List", "CategoryAdmin"));
        }

        [HttpPost]
        public ActionResult Save(Category category)
        {
            if (!ModelState.IsValid)
            {
                PopulateViewData(category.ID, category.ParentID ?? 0);
                return category.ID == 0 ? View("New", category) : View("Edit", category);
            }
            categories.Save(category);
            return RedirectToAction("List");
        }

        private void PopulateViewData(int ID, int selectedParentID)
        {
            var cats = categories.GetAll()
                .Where(x => x.ParentID == null && x.ID != ID)
                .OrderBy(x => x.Name)
                .Select(x => new SelectListItem()
                {
                    Text = x.Name,
                    Value = x.ID.ToString(),
                    Selected = x.ID == selectedParentID
                })
                .ToList();
            cats.Insert(0, new SelectListItem() { Text = "Root", Value = "0" });
            ViewData["cats"] = cats;
        }
    }
}
